package main

import (
	"fmt"
	"os"
	"sanguo/cluster"
	"sanguo/node/node_login"
	"strconv"
	"strings"

	"github.com/go-ini/ini"
	"github.com/sniperHW/kendynet"
	"github.com/sniperHW/kendynet/golog"
)

func main() {

	if len(os.Args) < 2 {
		fmt.Printf("usage ./node_login config\n")
		return
	}

	outLogger := golog.NewOutputLogger("log", "node_login", 1024*1024*50)
	kendynet.InitLogger(outLogger, "node_login")
	cluster.InitLogger(outLogger, "node_login")
	node_login.InitLogger(outLogger, "node_login")

	cfg, err := ini.LooseLoad(os.Args[1])
	if err != nil {
		node_login.Errorf("load %s failed:%s\n", os.Args[1], err.Error())
		return
	}

	cfgCommon := cfg.Section("Common")

	if nil == cfgCommon {
		node_login.Errorf("missing sec[Common]\n")
		return
	}

	sec := cfg.Section(os.Args[2])

	if nil == sec {
		node_login.Errorf("missing sec[%s]\n", os.Args[2])
		return
	}

	centerAddr := cfgCommon.Key("centerAddr").Value()
	areaID := cfgCommon.Key("areaID").Value()

	clusterAddr := sec.Key("clusterAddr").Value()
	externalAddr := sec.Key("externalAddr").Value()
	dirCenter := sec.Key("dirCenter").Value()

	t := strings.Split(clusterAddr, ":")

	ip := t[0]
	port, _ := strconv.Atoi(t[1])

	centerAddrs := strings.Split(centerAddr, ",")

	if "" != dirCenter {
		centerAddrs = append(centerAddrs, dirCenter)
	}

	err = cluster.Start(centerAddrs, cluster.MakeService("login", ip, int32(port)))

	if nil != err {
		node_login.Errorf("node_login start failed:%s\n", err.Error())
		return
	}

	err = node_login.Start(externalAddr, areaID)
	if nil != err {
		node_login.Errorf("node_login start failed:%s\n", err.Error())
	} else {
		node_login.Infof("node_login start on %s\n", externalAddr)

		sigStop := make(chan bool)
		_, _ = <-sigStop
	}
}
